import 'dart:io';

import 'package:FlutterStudy/model/post.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

class DataTableDemo extends StatefulWidget {
  @override
  _DataTableDemoState createState() {
    return _DataTableDemoState();
  }
}

class _DataTableDemoState extends State<DataTableDemo> {
  HttpClient? _httpClient;

  int _sortColumnIndex = 0;

  bool _sortAscending = false;

  @override
  void initState() {
    super.initState();
    // 初始化 HttpClient 并配置证书验证回调
    _httpClient = HttpClient()
      ..badCertificateCallback = (X509Certificate cert, String host, int port) {
        // 返回 true 允许不安全的证书，生产环境应更谨慎处理
        return true;
      };
  }

  @override
  void dispose() {
    // 关闭 HttpClient 释放资源
    _httpClient?.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return SingleChildScrollView(
      scrollDirection: Axis.vertical,
      child: DataTable(
        horizontalMargin: 10,
        columnSpacing: 10,
        onSelectAll: ( isAll){
          debugPrint("check All");
          setState(() {
            posts.forEach((post){
              post.selected=isAll!;
            });
          });

        },

        checkboxHorizontalMargin: 10,
        showCheckboxColumn: true,

        sortColumnIndex: _sortColumnIndex,
        sortAscending: _sortAscending,
        dataRowMinHeight: 80.0,
        // 设置数据行高度
        dataRowMaxHeight: 100,
        dataRowColor: WidgetStateProperty.resolveWith<Color?>((
          Set<WidgetState> states,
        ) {
          // 可以根据状态返回不同颜色，这里统一返回一个颜色
          return Colors.grey[200]; // 例如浅灰色
        }),

        columns: [
          DataColumn(
            // headingRowAlignment: MainAxisAlignment.center,
            onSort: (int columnIndex, bool ascending) {
              _sortPost(columnIndex, ascending);
            },
            label: Expanded(child: Text("标题")),
            numeric: false,
            columnWidth: FlexColumnWidth(1),
          ),
          DataColumn(
            headingRowAlignment: MainAxisAlignment.center,
            onSort: (int columnIndex, bool ascending) {
              _sortPost(columnIndex, ascending);
            },
            label: Text("作者"),
            numeric: false,
            columnWidth: FlexColumnWidth(1),
          ),
          DataColumn(
            headingRowAlignment: MainAxisAlignment.center,
            onSort: (int columnIndex, bool ascending) {
              _sortPost(columnIndex, ascending);
            },
            label: Text("图片"),
            numeric: false,
            columnWidth: FlexColumnWidth(1),
          ),
          DataColumn(
            onSort: (int columnIndex, bool ascending) {
              _sortPost(columnIndex, ascending);
            },
            label: Text("描述"),
            numeric: false,
            columnWidth: FlexColumnWidth(1),
          ),
        ],
        rows: posts.map((post) {
          return DataRow(
            selected: post.selected,
            onSelectChanged: (bool? selected) {
              setState(() {
                post.selected = selected ?? false; // 更新选中状态
              });
            },
            cells: [
              DataCell(
                placeholder: true,
                /*   SizedBox.expand(
                  child: Container(
                    width: double.infinity,
                    height: double.infinity,
                    constraints: BoxConstraints.expand(),
                    // 强制扩展到可用空间
                    color: Colors.green,
                    child: Text(post.title, style: TextStyle(fontSize: 10)),
                  ),
                )*/
                Text(post.title, style: TextStyle(fontSize: 10)),
              ),
              DataCell(Text(post.author)),
              DataCell(
                Image.network(
                  "https://resources.ninghao.net/images/candy-shop.jpg",
                  width: 30,
                  height: 30,
                  loadingBuilder: (context, child, loadingProgress) {
                    if (loadingProgress == null) return child;
                    return CircularProgressIndicator();
                  },
                  errorBuilder: (context, error, stackTrace) {
                    return Icon(Icons.error);
                  },
                ),
              ),
              DataCell(Text(post.description, style: TextStyle(fontSize: 10))),
            ],
          );
        }).toList(),
      ),
    );
  }

  void _sortPost(int columnIndex, bool ascending) {
    setState(() {
      _sortColumnIndex = columnIndex;
      _sortAscending = ascending;

      // 根据列索引和排序方向对posts进行排序
      posts.sort((Post a, Post b) {
        switch (columnIndex) {
          case 0: // 标题列
            return ascending
                ? a.title.compareTo(b.title)
                : b.title.compareTo(a.title);
          case 1: // 作者列
            return ascending
                ? a.author.compareTo(b.author)
                : b.author.compareTo(a.author);
          default:
            return 0;
        }
      });
    });
  }
}
